package com.imageim.yimirror.ui.fragment;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.bean.dailyPhoto.TryClothResultPhotoBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetListCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.ui.SpacesItemDecoration;
import com.imageim.yimirror.common.ui.dialog.PromptDialog;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.ClickUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.ui.activity.TakeMemoryPhotoNewActivity;
import com.imageim.yimirror.ui.activity.tryCloth.ChangePhotoBgActivity;
import com.imageim.yimirror.ui.adapter.tryCloth.TryClothResultPhotoAdapter;
import com.makeramen.roundedimageview.RoundedImageView;
import com.martin.ads.omoshiroilib.util.BitmapUtils;

import org.apache.http.message.BasicNameValuePair;
import org.byteam.superadapter.OnItemClickListener;
import org.byteam.superadapter.animation.SlideInRightAnimation;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 试穿留影合成背景列表
 * Created by Bruce.Zhou on 2018/11/22 11:36.
 * Email: 907160968@qq.com
 */
public class TryClothPhotoFragment extends BaseFragment {
    private static final String TAG = "ImagePhotoFragment";
    @BindView(R.id.rv_photo_list)
    RecyclerView rvPhotoList;
    @BindView(R.id.iv_share_qrcode)
    ImageView ivShareQrcode;
    @BindView(R.id.panel_qrcode)
    FrameLayout panelQrcode;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_takepic)
    TextView tvTakepic;
    @BindView(R.id.panel_empty)
    LinearLayout panelEmpty;
    @BindView(R.id.iv_photo_bg)
    RoundedImageView ivPhotoBg;
    @BindView(R.id.btn_select_scene)
    Button mBtnSelectScene;
    @BindView(R.id.iv_btn_share)
    ImageView mIvBtnShare;
    @BindView(R.id.btn_addUserPhoto)
    LinearLayout mBtnAddUserPhoto;
    private TryClothResultPhotoAdapter mAdapter;
    TryClothResultPhotoBean memPhotoBean; // 保存当前选择的照片
    private int currIndex;

    @Override
    protected int getLayoutId() {
        return R.layout.try_cloth_photo_fragment;
    }

    @Override
    protected void initListener() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvPhotoList.setLayoutManager(linearLayoutManager);
        rvPhotoList.addItemDecoration(new SpacesItemDecoration(4));
        List<TryClothResultPhotoBean> photoList = new ArrayList<>();
        mAdapter = new TryClothResultPhotoAdapter(getContext(), photoList, R.layout.item_try_cloth_result_photo);
        mAdapter.enableLoadAnimation(500, new SlideInRightAnimation());
        rvPhotoList.setAdapter(mAdapter);
        mAdapter.getData().add(new TryClothResultPhotoBean());
        mAdapter.notifyDataSetChanged();
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int viewType, int position) {
                if (ClickUtil.isValidClick(500) && position < mAdapter.getData().size()) {
                    memPhotoBean = mAdapter.getData().get(position);
                    currIndex = position;
                    String imageUrl = memPhotoBean.getBodyComposeImage();
                    if (TextUtils.isEmpty(imageUrl)) {
                        imageUrl = memPhotoBean.getPhotoUrl();
                    }
                    GlideUtils.display(ivPhotoBg, imageUrl);
                    mAdapter.select(position);
                }
            }
        });

        getPhotoList(true);
    }

    @Override
    protected void initData() {
        panelQrcode.setVisibility(View.GONE);
    }

    @Override
    public void onEventMainThread(EventMessage event) {
        switch (event.getCode()) {
            case EventCode.CODE_UPDATE_MEMPHOTO_LIST: // 刷新相册
                boolean isRefresh = (boolean) event.getValue();
                getPhotoList(isRefresh);
                break;
            default:
        }
    }


    /**
     * 跳转拍照界面
     */
    private void gotoTakePhoto() {
        //        Bundle data = new Bundle();
        //        data.putInt(Constants.TO_DO_FLAG, Constants.Action.UPLOAD_DAILY_PHOTO_RECORD);
        SceneManager.toScene(getContext(), TakeMemoryPhotoNewActivity.class, null);
    }


    @OnClick({R.id.btn_addUserPhoto, R.id.tv_takepic, R.id.iv_btn_share, R.id.btn_select_scene})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_addUserPhoto:
                gotoTakePhoto();
                break;
            case R.id.tv_takepic:
                gotoTakePhoto();
                break;
            case R.id.iv_btn_share:
                //                if (panelQrcode.getVisibility() == View.VISIBLE) {
                //                    panelQrcode.setVisibility(View.GONE);
                //                } else {
                //                    panelQrcode.setVisibility(View.VISIBLE);
                //                }
                showShareDialog();
                break;
            case R.id.btn_select_scene:
                Bundle data = new Bundle();
                data.putSerializable(ChangePhotoBgActivity.MEM_PHOTO_BEAN, memPhotoBean);
                data.putInt("from", 2);
                SceneManager.toScene(getContext(), ChangePhotoBgActivity.class, data);
                break;
            default:
        }
    }

    private void showShareDialog() {
        PromptDialog dialog = new PromptDialog(getContext());
        dialog.setOutsideCanelable(true);
        dialog.bindView(R.layout.layout_share_dialog, new PromptDialog.BindViewListener() {
            @Override
            public void onBindView(View contentView) {
                ImageView iv = contentView.findViewById(R.id.iv_qrcode);
                String content = mAdapter.getData().get(currIndex).getQrcode();
                if (TextUtils.isEmpty(content)) {
                    content = "服务器没有返回内容";
                }
                Bitmap bitmap = BitmapUtils.getQrcodeBitmapWithPadding(content, 460,
                        Color.BLACK, 18);
                iv.setImageBitmap(bitmap);
            }
        });
        dialog.show();
    }

    private void showEmptyView() {
        if (panelEmpty != null) {
            panelEmpty.setVisibility(View.VISIBLE);
        }
    }

    private void hideEmptyView() {
        if (panelEmpty != null) {
            panelEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 获取我的试穿留影历史列表
     */
    private void getPhotoList(boolean isFirstRefresh) {
        List<BasicNameValuePair> params = new ParamCreator().add("userId", UserUtil.getUserId())
                .add("photoNo", UserUtil.getPhotoNo()).build();
        NetUtil.getList(getContext(), NetConstants.URL.GET_MEM_PHOTO_LIST, params, new NetListCallback<TryClothResultPhotoBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(List<TryClothResultPhotoBean> result) {
                if (result != null && result.size() > 0) {
                    mAdapter.getData().clear();
                    mAdapter.getData().addAll(result);
                    if (isFirstRefresh) {
                        memPhotoBean = result.get(0);
                        rvPhotoList.scrollToPosition(0);
                        if (!TextUtils.isEmpty(memPhotoBean.getBodyComposeImage())) {
                            GlideUtils.display(ivPhotoBg, memPhotoBean.getBodyComposeImage());
                        } else {
                            GlideUtils.display(ivPhotoBg, memPhotoBean.getPhotoUrl());
                        }
                        mAdapter.select(0);
                    } else {
                        mAdapter.notifyDataSetChanged();
                        mAdapter.select(currIndex);
                        memPhotoBean = result.get(currIndex);
                        GlideUtils.display(ivPhotoBg, memPhotoBean.getBodyComposeImage());
                    }
                }
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + errorCode);
            }
        }, TryClothResultPhotoBean.class);
    }
}